package com.hubu;
import com.hubu.json.Command;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
/**
 * 将一个对应的命令处理成为一个buffer
 */


public class CommandHelper {
    public byte[] parseCommand(Command command){
        if(command==null) return null;
        Set<String> names=new HashSet<>();
        List<String> nameList=new ArrayList<>();
        int count=0;
        Class<? extends Command> aClass = command.getClass();
        Method[] methods;
        Field fields[]=aClass.getDeclaredFields();
        for(Field item:fields){
            if(item!=null){
                names.add(item.getName());
            }
        }
        methods = aClass.getDeclaredMethods();
        for(Method method:methods){
            method.setAccessible(true);
            String name = method.getName();
            if(name!=null&&name.startsWith("get")){
                String fieldName = name.substring(3, name.length());
                //确定是get方法
                byte[] bf = fieldName.getBytes();
                byte zero=bf[0];
                zero+=32;
                bf[0]=zero;
                String f=new String(bf);
                if(names.contains(f)){
                    try {
                        Object o= method.invoke(command);
                        if(o instanceof String){
                            String iter= (String) o;
                            nameList.add(iter);
                        }
                        if(o!=null) count++;
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("#");
        stringBuilder.append(count);
        for(String item:nameList){
            if(item!=null&&item.length()>0){
                stringBuilder.append("$");
                stringBuilder.append(item.length());
                stringBuilder.append(item);
            }
        }
        String result=stringBuilder.toString();
        System.out.println(result);
        return result.getBytes(StandardCharsets.UTF_8);
    }
    public static void main(String[] args) {
        Command c=new Command();
        c.setValue("lugang");
        c.setKey("name");
        c.setCommandType("put");
        CommandHelper commandHelper=new CommandHelper();
        commandHelper.parseCommand(c);
    }
}

